package cn.iocoder.yudao.module.vos.job;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.module.vos.service.marketingscore.admin.MarketingScoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@Component
@Slf4j
public class MarketingScoreBuildJob implements JobHandler {

    @Resource
    private MarketingScoreService scoringService;

    /**
     * param 格式举例：
     * 1) "" 或 null           -> 默认构建“昨天”
     * 2) "day=20250828"       -> 构建指定日期
     * 3) "range=20250825,20250828" -> 构建 [25..28] 每天
     * 4) "rebuild=true&day=20250828" -> 先清空再重算该天
     * cooldownDays = 7 如果某手机号在前 N 天（不含当天）的 Mongo 里出现过（有记录即可），就不写入当天的评分分表
     */
    @Override
    public String execute(String param)  {
        Map<String, String> p = Query.parse(param);
        String day = p.get("day");
        String range = p.get("range");
        int cooldownDays = Integer.parseInt(p.getOrDefault("cooldownDays", "7"));
        boolean rebuild = "true".equalsIgnoreCase(p.getOrDefault("rebuild", "false"));
        int built = 0;
        if (range != null && !range.isEmpty()) {
            String[] arr = range.split(",");
            if (arr.length == 2) {
                String s = ScoreTableJob.toDay8(arr[0]);
                String e = ScoreTableJob.toDay8(arr[1]);
                LocalDate cur = toDate(s), end = toDate(e);
                while (!cur.isAfter(end)) {
                    String d = cur.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
                    if (rebuild) scoringService.rebuildDayScores(d, cooldownDays);
                    else scoringService.buildDayScores(d, cooldownDays);
                    built++;
                    cur = cur.plusDays(1);
                }
                return "built days: " + built;
            }
        }
        if (day == null || day.isEmpty()) {
            String y = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            if (rebuild) scoringService.rebuildDayScores(y , cooldownDays);
            else scoringService.buildDayScores(y,cooldownDays);
            return "built day: " + y;
        } else {
            String d = ScoreTableJob.toDay8(day);
            if (rebuild) scoringService.rebuildDayScores(d, cooldownDays);
            else scoringService.buildDayScores(d, cooldownDays);
            return "built day: " + d;
        }
    }

    private static LocalDate toDate(String yyyymmdd) {
        return LocalDate.of(
                Integer.parseInt(yyyymmdd.substring(0,4)),
                Integer.parseInt(yyyymmdd.substring(4,6)),
                Integer.parseInt(yyyymmdd.substring(6,8)));
    }

    /** 简易查询串解析：k1=v1&k2=v2... */
    static class Query {
        static Map<String, String> parse(String s) {
            java.util.HashMap<String,String> m = new java.util.HashMap<>();
            if (s == null || s.trim().isEmpty()) return m;
            for (String kv : s.split("&")) {
                if (kv.isEmpty()) continue;
                int i = kv.indexOf('=');
                if (i < 0) m.put(kv.trim(), "");
                else m.put(kv.substring(0,i).trim(), kv.substring(i+1).trim());
            }
            return m;
        }
    }
}
